const hx = require('hbuilderx')
const util = require('util')
const pino = require('pino')
const rfs = require('rotating-file-stream')
const { join } = require('path')
const _ = require('lodash')

const loggers = new Map()
const name = 'Linux 服务器运维助手'
const duration = 10 * 1000

const outputChannel = hx.window.createOutputChannel(name)

function format(msg, args) {
    return util.format(msg, ...args)
}

function info(msg) {
    outputChannel.appendLine(msg)
}

function statusBarInf(msg, ...args) {
    hx.window.setStatusBarMessage(format(msg, args), duration, 'info')
}
function statusBarErr(msg, ...args) {
    hx.window.setStatusBarMessage(format(msg, args), duration, 'error')
}
function show() {
    outputChannel.show()
}

function clear() {
    hx.window.clearStatusBarMessage()
}

class ContinuousLogger {
    _logs = []
    _format(msg, args) {
        const text = util.format(msg, ...args)
        this._logs.push(text)
        return text
    }
    inf(msg, ...args) {
        hx.window.setStatusBarMessage(this._format(msg, args), duration, 'info')
    }
    wan(msg, ...args) {
        hx.window.setStatusBarMessage(this._format(msg, args), duration, 'info')
    }
    err(msg, ...args) {
        hx.window.setStatusBarMessage(this._format(msg, args), duration, 'info')
    }
    async showDetail(title, btns) {
        const name = await hx.window.showInformationMessage(title, btns)
        if (name == '详情') {
            outputChannel.show()
            this._logs.forEach(log => {
                outputChannel.appendLine(log)
            })
        }
        return name
    }
    async showError(title, btns) {
        const name = await hx.window.showErrorMessage(title, btns)
        if (name == '详情') {
            outputChannel.show()
            this._logs.forEach(log => {
                outputChannel.appendLine(log)
            })
        }
        return name
    }
    static create() {
        return new ContinuousLogger()
    }
}

function createFileLogger(path, name) {
    if (loggers.has(name)) {
        return loggers.get(name)
    }
    const opts = {
        name: name,
        stream: {
            path: path || join(process.cwd(), 'logs'),
            size: '10M',
            interval: '1M',
            compress: 'gzip',
            encoding: 'utf8'
        }
    }
    const stream = rfs.createStream(opts.name, opts.stream)
    loggers.set(name, pino(stream))
    return loggers.get(name)
}

const notice = {
    info(msg, ...args) {
        hx.window.showInformationMessage(format(msg, args))
    },
    warn(msg, ...args) {
        hx.window.showWarningMessage(format(msg, args))
    },
    error(msg, ...args) {
        hx.window.showErrorMessage(format(msg, args))
    }
}

module.exports = {
    info,
    show,
    statusBarInf,
    statusBarErr,
    ContinuousLogger,
    clear,
    createFileLogger,
    notice
}
